import { useState } from 'react'
import './index.scss'

const initItem = [
  '','','','',
  '🐎','🐏','🐕','',
  '','','',''
]

const Item = ({item, index, source, target, onDragStart, onDragOver, onDragLeave, onDragEnd}) => {
  return (
    <div
      className={target===index?'placehoder highlight':'placehoder'}
      onDragOver={onDragOver}
      onDragLeave={onDragLeave}
    >
      <div
        className={source===index?'item_container current':'item_container'}
        draggable={item!==''}
        onDragStart={onDragStart}
        onDragEnd={onDragEnd}
      >
        {
          item && <div className='card'>{item}</div>
        }
      </div>
    </div>
  )
}

const Index = () => {
  const [items, setItems] = useState(initItem)
  const [source, setSource] = useState(null)
  const [target, setTarget] = useState(null)

  const onDragStart = (index) => (e) => {
    // console.log(index, e)
    setSource(index)
  }

  const onDragOver = (index) => (e) => {
    // console.log(index, e)
    // setTarget(index)
  }

  const onDragLeave = (index) => (e) => {
    // console.log(index, e)
    setTarget(index)
  }

  const onDragEnd = () => {
    console.log(target, source);
    if (target!==null && source !== null && target !== source) {
      const arr = [...items]
      const str = arr[target]
      arr[target] = arr[source]
      arr[source] = str
      setItems(arr)
    }
    setSource(null)
    setTarget(null)
  }

  return (
    <div className='index' style={{ backgroundColor: 'slategray' }}>
      <div className='wrapper'>
        {
          items.map((item, index) =>
            <Item
              key={index}
              item={item}
              index={index}
              source={source}
              target={target}
              onDragStart={onDragStart(index)}
              onDragOver={onDragOver(index)}
              onDragLeave={onDragLeave(index)}
              onDragEnd={onDragEnd}
            />
          )
        }
      </div>
    </div>
  )
}

export default Index